

#import "BriefController.h"
#import "NSMPhotosView.h"
#import "RegistController.h"

@interface BriefController () <UITextFieldDelegate>
@property (nonatomic, strong) UITextField *nicknameField;
@property (nonatomic, strong) UITextField *sexField;
@property (nonatomic, strong) NSMPhotosView *photosView;
@property (nonatomic) BOOL avatarDidChanged;
@end

@implementation BriefController

- (void)didInitialize {
    [super didInitialize];
}

- (void)loadView {
    self.view = [UIScrollView new];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = THEME_COLOR;
    
    @nsm_weak(self)
    [_appCache refreshUserInfo:^(id obj) {
        @nsm_strong(self)
        [self setupUI];
    } hud:YES];
}

- (void)setupUI {
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"保存"
                                                                  style:UIBarButtonItemStylePlain
                                                                 target:self
                                                                 action:@selector(submit)];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.myHorzMargin = 0;
    layout.padding = UIEdgeInsetsMake(20, 0, 20, 0);
    layout.gravity = MyGravity_Horz_Center;
    [self.view addSubview:layout];
    
    UIView *avatar = [UIView new];
    avatar.backgroundColor = COLOR_4;
    avatar.mySize = CGSizeMake(120, 120);
    [layout addSubview:avatar];
    ViewCorner(avatar, 60);
    ViewBorder(avatar, 4, COLOR_4);
    
    UIImage *placeholderImage = kPlaceholderImage;
    
    _photosView = [NSMPhotosView photoView];
    _photosView.padding = UIEdgeInsetsZero;
    _photosView.arrangedCount = 1;
    _photosView.maximumNumberOfPhotos = 1;
    _photosView.editEnabled = YES;
    _photosView.deleteEnabled = NO;
    _photosView.addImage = placeholderImage;
    _photosView.placeholderImage = placeholderImage;
    if (_appCache.userInfo.avatarURL)
        _photosView.originPhotos = @[_appCache.userInfo.avatarURL];
    @nsm_weak(self)
    _photosView.photosDidChanged = ^{
        @nsm_strong(self)
        self.avatarDidChanged = YES;
        [self checkEnable];
    };
    [avatar addSubview:_photosView];
    
    UILabel *tip = [UILabel new];
    tip.text = @"点击修改头像";
    tip.font = CustomFont(14);
    tip.myTop = 12;
    tip.textColor = COLOR_3;
    tip.wrapContentSize = YES;
    [layout addSubview:tip];
    
    NSString *sexName = @"";
    if (_appCache.userInfo.sex == 1)
        sexName = @"男";
    else if (_appCache.userInfo.sex == 2)
        sexName = @"女";
    NSArray *items = @[@{@"title": @"昵    称     ",
                         @"placeholder": @"输入昵称",
                         @"text": SafeString(_appCache.userInfo.nickName),
                         @"tag": @(0)},
                       @{@"title": @"性    别     ",
                         @"placeholder": @"选择性别",
                         @"text": sexName,
                         @"tag": @(1)}];
    for (NSDictionary *item in items) {
        NSInteger tag = [item[@"tag"] integerValue];
        
        UITextField *textField = UITextField.new;
        textField.myHorzMargin = 15;
        textField.myHeight = 44;
        textField.delegate = self;
        textField.tag = tag;
        textField.font = CustomFont(14);
        textField.textColor = COLOR_4;
        textField.textAlignment = NSTextAlignmentRight;
        textField.placeholder = item[@"placeholder"];
        [textField setValue:COLOR_3 forKeyPath:@"_placeholderLabel.textColor"];
        textField.text = item[@"text"];
        [layout addSubview:textField];
        
        UILabel *titleLabel = UILabel.new;
        titleLabel.width = CGFLOAT_MAX;
        titleLabel.font = SystemFont(15);
        titleLabel.textColor = COLOR_4;
        titleLabel.text = item[@"title"];
        [titleLabel sizeToFit];
        
        textField.leftView = titleLabel;
        textField.leftViewMode = UITextFieldViewModeAlways;
        
        UIView *line = UIView.new;
        line.backgroundColor = THEME_LINE_COLOR;
        line.myHorzMargin = 15;
        line.myHeight = kSinglePixel;
        [layout addSubview:line];
        
        if (tag==0) {
            textField.tintColor = THEME_TEXT_COLOR;
            [textField addBlockForControlEvents:UIControlEventAllEditingEvents block:^(UITextField *sender) {
                [self checkEnable];
            }];
            self.nicknameField = textField;
            
            // 昵称备注
            UILabel *tipLabel = UILabel.new;
            tipLabel.text = @"最长7个字符,不能包含特殊符号";
            tipLabel.font = CustomFont(13);
            tipLabel.myTop = 4;
            tipLabel.myBottom = 5;
            tipLabel.textColor = COLOR_3;
            tipLabel.myHorzMargin = 15;
            tipLabel.wrapContentHeight = YES;
            [layout addSubview:tipLabel];
        }
        else if (tag == 1) {
            self.sexField = textField;
            
            // 箭头
            UIView *rightView = UIView.new;
            UIImageView *arrow = ArrowImageView(COLOR_4, 1);
            arrow.left = 7;
            [rightView addSubview:arrow];
            rightView.size = CGSizeMake(arrow.right, arrow.height);
            textField.rightView = rightView;
            textField.rightViewMode = UITextFieldViewModeAlways;
        }
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self.view endEditing:YES];
    
    NSInteger tag = textField.tag;
    @nsm_weak(self)
    if (tag == 1) {
        // 选择性别
        UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *male = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            @nsm_strong(self)
            textField.text = action.title;
            [self checkEnable];
        }];
        UIAlertAction *female = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            @nsm_strong(self)
            textField.text = action.title;
            [self checkEnable];
        }];
        UIAlertAction *secret = [UIAlertAction actionWithTitle:@"不显示" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            @nsm_strong(self)
            textField.text = action.title;
            [self checkEnable];
        }];
        if ([textField.text isEqual:@"男"])
            [male setValue:UIColor.redColor forKey:@"titleTextColor"];
        else if ([textField.text isEqual:@"女"])
            [female setValue:UIColor.redColor forKey:@"titleTextColor"];
        else
            [secret setValue:UIColor.redColor forKey:@"titleTextColor"];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [actionSheet addAction:male];
        [actionSheet addAction:female];
        [actionSheet addAction:secret];
        [actionSheet addAction:cancel];
        [self presentViewController:actionSheet animated:YES completion:nil];
        return NO;
    }
    return YES;
}

#pragma mark - method
- (void)checkEnable {
    BOOL enabled = NO;
    
    NSString *sexName = @"不显示";
    if (_appCache.userInfo.sex == 1)
        sexName = @"男";
    else if (_appCache.userInfo.sex == 2)
        sexName = @"女";
    if (_nicknameField.enabled) {
        // 允许修改昵称
        BOOL isEqual = [_nicknameField.text isEqual:_appCache.userInfo.nickName];
        enabled = ((_nicknameField.text.length && _nicknameField.text.length<=7 && !isEqual) ||
                   (_sexField.text.length && ![_sexField.text isEqual:sexName]) ||
                   _avatarDidChanged);
    } else {
        // 不允许修改昵称,只判断图片/性别有没有修改即可
        enabled = ((_sexField.text.length && ![_sexField.text isEqual:sexName]) ||
                   _avatarDidChanged);
    }
    self.navigationItem.rightBarButtonItem.enabled = enabled;
}

#pragma mark - action
- (void)submit {
    [self.view endEditing:YES];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:_keyWindow animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.backgroundColor = THEME_LINE_COLOR;
    hud.margin = 12;
    hud.label.font = SystemFont(14);
    hud.label.textColor = COLOR_4;
    hud.label.text = @"正在保存";
    
    NSData *imageData;
    if (self.avatarDidChanged) {
        if (self.photosView.photoViews.count) {
            NSMPhotoImageView *imageView = self.photosView.photoViews.firstObject;
            if (!imageView.isOrigin)
               imageData = [imageView.image nsm_compressWithMaxLength:kMaxUploadImageDataLength];
        }
    }
    
    if (imageData) {
        hud.mode = MBProgressHUDModeAnnularDeterminate;
    }
    
    NSDictionary *param = @{@"nickname" : SafeString(_nicknameField.text),
                            @"sex": [_sexField.text isEqual:@"女"]?@"2":@"1"};
    @nsm_weak(self)
    [_networker POST:@"mine/center" parameters:param formDataBlock:^(id<AFMultipartFormData> formData) {
        if (!imageData) return;
        [formData appendPartWithFileData:imageData
                                    name:@"headpic"
                                fileName:@"headpic.jpg"
                                mimeType:@"image/jpeg"];
    } progress:^(NSProgress *uploadProgress) {
        dispatch_async_on_main_queue(^{
            hud.progress = uploadProgress.fractionCompleted;
        });
    } success:^(NSMResponseObject *responseObject) {
        @nsm_strong(self)
        !self.didEditSuccess?:self.didEditSuccess(responseObject);
        
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:BundleTemplateImage(@"MBHUD_Success")];
        hud.label.text = @"保存成功";
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud hideAnimated:YES];
            [self.navigationController popViewControllerAnimated:YES];
        });
    } empty:^(NSMResponseObject *responseObject) {
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:BundleTemplateImage(@"MBHUD_Error")];
        hud.label.text = @"保存失败";
        [hud hideAnimated:YES afterDelay:1];
    } failure:^(NSError *error) {
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:BundleTemplateImage(@"MBHUD_Error")];
        hud.label.text = @"保存失败";
        [hud hideAnimated:YES afterDelay:1];
    } hud:NO];
}

@end
